import { AUTHORIZATION_TOKEN, ROUTE_PATHS } from "@/constants/common";

interface RequestOptions extends RequestInit {
  params?: Record<string, any>; // 添加 params 选项
}

export const request = async (url: string, options: RequestOptions = {}): Promise<any> => {
  const { params, ...fetchOptions } = options;

  // 如果是 GET 请求且有 params，构建查询字符串
  let fullUrl = import.meta.env.VITE_APP_API_URL + url;
  if (params && Object.keys(params).length > 0) {
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== "") {
        queryParams.append(key, String(value));
      }
    });
    const queryString = queryParams.toString();
    if (queryString) {
      fullUrl += (url.includes("?") ? "&" : "?") + queryString;
    }
  }

  // 只对非登录和注册接口检查 token
  const token = localStorage.getItem(`${AUTHORIZATION_TOKEN}`);
  if (!token && !url.includes("/login") && !url.includes("/v1/admin/user")) {
    return (window.location.href = `${window.location.origin}${ROUTE_PATHS.login}`);
  }

  return new Promise((resolve, reject) => {
    fetch(fullUrl, {
      ...fetchOptions,
      headers: {
        "Content-Type": "application/json",
        [AUTHORIZATION_TOKEN]: token ? `${token}` : "",
      },
    })
      .then((response) => {
        if (response.status === 401) {
          localStorage.removeItem(`${AUTHORIZATION_TOKEN}`);
          return (window.location.href = `${window.location.origin}${ROUTE_PATHS.login}`);
        }
        if (!response.ok) {
          const error = new Error(`请求失败: ${response.status}`);
          (error as any).status = response.status;
          throw error;
        }
        return response.json();
      })
      .then((data) => resolve(data))
      .catch((error) => {
        console.log("error: ", error);
        reject(error);
      });
  });
};
